package com.wangmeng.book.job;

import com.wangmeng.book.dao.BaseDaoSupport;
import com.wangmeng.book.entity.BookDoc;
import com.wangmeng.book.updater.BookFromSina;
import com.wangmeng.book.updater.BookFromSohu;
import com.wangmeng.book.updater.BookFromTx;
import com.wangmeng.book.updater.BookFromWy;
import com.wangmeng.book.utils.ConstValueUtils;
import com.wangmeng.book.utils.SpringContextManager;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * User: 王猛
 * Date: 13-9-29
 * 未完结的内容更新检查
 */
public class ContentUpdateJob implements Runnable {
    private static final Logger logger = Logger.getLogger(ContentUpdateJob.class);

    public void run() {
        logger.info("内容更新检查开始");
        try {
            BaseDaoSupport daoSupport = SpringContextManager.getContext().getBean(BaseDaoSupport.class);
            List<BookDoc> bookList = daoSupport.listEntityByCondition(BookDoc.class, " and approveStatus = ? and status = ? ", new Object[]{ConstValueUtils.APPROVE_PUBLISH_SUCCESS,ConstValueUtils.STATUS_CONTINUE});
            BookFromTx bft = new BookFromTx();
            BookFromSina bfs = new BookFromSina();
            BookFromWy bfw = new BookFromWy();
            BookFromSohu bfu = new BookFromSohu();
            for (BookDoc bd : bookList) {
                int sType = bd.getSourceType();
                int backCode = ConstValueUtils.CODE_EXCEPTION;
                switch (sType) {
                    case ConstValueUtils.SOURCE_TYPE_TX: {
                        backCode = bft.updateContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_SN: {
                        backCode = bfs.updateContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_WY: {
                        backCode = bfw.updateContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_SH: {
                        backCode = bfu.updateContent(bd);
                        break;
                    }
                }
                if (backCode > ConstValueUtils.CODE_SUCCESS) {
                    if (bd.getApproveStatus() == ConstValueUtils.APPROVE_PUBLISH_SUCCESS) {
                        bd.setApproveStatus(ConstValueUtils.APPROVE_HAS_UPDATE);
                        daoSupport.saveEntity(bd);
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("内容更新检查异常", ex);
        } finally {
            logger.info("内容更新检查结束");
        }
    }
}
